#pragma once
#include <iostream>
#include"Err.hpp"
#include"Log.hpp"
#include<sys/epoll.h>
#include<errno.h>
#include<string.h>

class Epoll
{
    const static int defaultepfd=-1;
    const static int size=128;
public:
    Epoll(int epfd=defaultepfd)
    :_epfd(epfd)
    {
    }
    ~Epoll()
    {
        if(_epfd != defaultepfd) close(_epfd); 
    }

    void create()
    {
        // 参数只需要是一个大于0的整数就行 ，目前暂无其他的意义
        _epfd=epoll_create(size);
        if(_epfd<0)
        {
            logMessage(FATAL,"epoll_create error, code: %d, errstring: %s",strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }

    bool addEvent(int sock,uint32_t event)
    {
        struct epoll_event ev;
        ev.events=event;
        ev.data.fd=sock;
        int n = epoll_ctl(_epfd,EPOLL_CTL_ADD,sock,&ev);
        return n==0;
    }

    int Wait(struct epoll_event recv[],int num,int timeout)
    {
        int n = epoll_wait(_epfd,recv,num,timeout);
        return n;
    }

    bool control(int sock,uint32_t event,int action)
    {
        int n =0;
        if(action == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.events=event;
            ev.data.fd=sock;
            n = epoll_ctl(_epfd,action,sock,&ev);
        }else if(action== EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, action, sock, nullptr);
        }
        else{
            n=-1;
        }
        return n==0;

    }

    void Close()
    {
        if(_epfd != defaultepfd)
        {
            close(_epfd); 
        }
    }

    

private:
    int _epfd;
};